// pages/date/date.js
import Toast from 'tdesign-miniprogram/toast/index';
const {
  ganntdata,
  colorMap,
  colorList,
  dayWeek
} = require("../index/mock");
const {
  sumTimetoHour
} = require('../../utils/calender');
const MAX_WIDTH = 24;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tempIndex: [],
    selectStartDate: '',
    selectEndDate: '',
    ganntdata: {},
    CELL_WIDTH: 100,
    colorMap,
    currType: 'hour', //按天设置还是批量设置
    detailInfoVisible: false,
    navList: [{
        label: '按天设置',
        value: 'hour'
      },
      {
        label: '批量设置',
        value: 'day'
      },
    ],
    dayweek: dayWeek,
    colorList,
    viewDateList: [],
    dateValue: [],
    dateVisible: false,
    reasonVisible: false,
    cityValue: '',
    reasons: [{
        label: '维修保养',
        value: '1'
      },
      {
        label: '车辆出险',
        value: '2'
      },
      {
        label: '车辆借调',
        value: '3'
      },
      {
        label: '线下租车',
        value: '4'
      },
      {
        label: '其他',
        value: '5'
      },
    ],
    times: [{
        label: '00:00',
        value: '0'
      },
      {
        label: '01:00',
        value: '1'
      },
      {
        label: '02:00',
        value: '2'
      },
      {
        label: '03:00',
        value: '3'
      },
      {
        label: '04:00',
        value: '4'
      },
      {
        label: '05:00',
        value: '5'
      },
      {
        label: '06:00',
        value: '6'
      },
      {
        label: '07:00',
        value: '7'
      },
      {
        label: '08:00',
        value: '8'
      },
      {
        label: '09:00',
        value: '9'
      },
      {
        label: '10:00',
        value: '10'
      },
      {
        label: '11:00',
        value: '11'
      },
      {
        label: '12:00',
        value: '12'
      },
      {
        label: '13:00',
        value: '13'
      },
      {
        label: '14:00',
        value: '14'
      },
      {
        label: '15:00',
        value: '15'
      },
      {
        label: '16:00',
        value: '16'
      },
      {
        label: '17:00',
        value: '17'
      },
      {
        label: '18:00',
        value: '18'
      },
      {
        label: '19:00',
        value: '19'
      },
      {
        label: '20:00',
        value: '20'
      },
      {
        label: '21:00',
        value: '21'
      },
      {
        label: '22:00',
        value: '22'
      },
      {
        label: '23:00',
        value: '23'
      },
    ],
    year: new Date().getFullYear(),
    month: new Date().getMonth(),
    tstartDate:'',
    tendDate: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    console.log(options.carid)
    this.setData({
      ganntdata: ganntdata[0].childs[0]
    })
    this.initViewDate();
  },
  prevMonth() {
    console.log(this.data.month)
    if (this.data.month > 0) {
      this.setData({
        month: --this.data.month
      })
    } else {
      this.setData({
        year: --this.data.year,
        month: 11
      })
    }
    this.initViewDate();
  },
  nextMonth() {
    if (this.data.month < 11) {
      this.setData({
        month: ++this.data.month
      })
    } else {
      this.setData({
        year: ++this.data.year,
        month: 0
      })
    }
    this.initViewDate();
  },
  initViewDate() {
    var viewDateList = [];
    var year = this.data.year;
    var month = this.data.month;
    var monthDay = this.onGetCurrDays(year, month);
    var nullDay = this.onGetMonthFirstWeek(year, month);
    var ganntdata = this.data.ganntdata;
    for (let i = 0; i < nullDay; i++) {
      viewDateList.push('')
    }
    for (let i = 0; i < monthDay; i++) {
      var cellStartDate = new Date(new Date(year, month, i + 1).toLocaleDateString()).getTime();
      var cellEndDate = cellStartDate + 24 * 60 * 60 * 1000 - 1;
      // 保证日期的唯一性
      let obj = {
        hour: 0,
        left: 0,
        date: i + 1,
        type: 0
      };
      viewDateList.push(obj)
      ganntdata.useDate.forEach((item, index) => {
        var startDate = new Date(item.startDate - 0).getTime();
        var endDate = new Date(item.endDate - 0).getTime();
        // 如果开始时间大于这个格子的结束时间 就证明不会在这个格子上进行渲染
        // 如果结束时间小于这个格子的开始时间 就证明不会在这个格子上进行渲染
        if (startDate > cellEndDate || endDate < cellStartDate) return;
        // 这时候说明沾满这个格子5
        if (startDate <= cellStartDate && endDate > cellEndDate) {
          obj.hour = MAX_WIDTH;
          obj.type = item.type;
          obj.tindex = index;
        }
        if (startDate > cellStartDate && startDate < cellEndDate) {
          let width = 0;
          // 只占后侧  2/27
          if (endDate > cellEndDate) {
            width = sumTimetoHour(cellEndDate - startDate) + 1;
          }
          // 只占中间部分
          if (endDate <= cellEndDate) {
            width = sumTimetoHour(endDate - startDate);
          }
          obj.hour = width;
          obj.left = sumTimetoHour(startDate - cellStartDate);
          obj.type = item.type;
          obj.tindex = index;
        }
        if (startDate < cellStartDate && endDate < cellEndDate && endDate > cellStartDate) {
          // 只占前侧
          const width = sumTimetoHour(endDate - cellStartDate)
          obj.hour = width;
          obj.type = item.type
          obj.tindex = index;
        }
      })
      // viewDateList.push(i + 1)
    }
    this.setData({
      viewDateList
    })
    console.log(nullDay)
  },
  // 获取当月有多少天
  onGetCurrDays(year, month) {
    // month: 几月
    if (month !== 1) {
      const months = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
      return months[month]
    }
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ? 29 : 28
  },
  // 计算当月的第一天是周几，返回需要该空出的格数
  onGetMonthFirstWeek(year, month) {
    const firstDayWeek = new Date(year, month, 1).getDay()
    return firstDayWeek === 0 ? 0 : firstDayWeek
  },
  onChangeType(e) {
    console.log(e)
    var {
      type
    } = e.currentTarget.dataset;
    this.setData({
      currType: type
    })
  },
  closeDetailInfoVisible() {
    this.setData({
      detailInfoVisible: false
    })
  },
  onColumnChange(e) {
    console.log('picker pick:', e);
  },
  onPickerChange(e) {
    const {
      key
    } = e.currentTarget.dataset;
    const {
      value
    } = e.detail;
    var viewDateList = this.data.viewDateList;
    var tempIndex = this.data.tempIndex;
    var type = this.data.currType;
    var selectStartDate = this.data.selectStartDate;
    var selectEndDate = this.data.selectEndDate;
    var dateValue = this.data.dateValue;
    var ganntdata = this.data.ganntdata;
    var year = this.data.year;
    var month = this.data.month;
    var day = new Date(selectStartDate).getDate();

    if (key == 'date') {
      console.log(value)
      this.setData({
        reasonVisible: true
      })
    }
    if (key == 'reason') {
      if (type == 'hour') {
        debugger
        if (dateValue[0] > dateValue[1]) {
          ganntdata.useDate.push({
            startDate: new Date(year, month, day, dateValue[1], 0),
            endDate: new Date(year, month, day, dateValue[0], 0),
            type: value[0]
          })
        } else {
          ganntdata.useDate.push({
            startDate: new Date(year, month, day, dateValue[0], 0),
            endDate: new Date(year, month, day, dateValue[1], 0),
            type: value[0]
          })
        }
      } else {
        var startYear = new Date(selectStartDate).getFullYear();
        var startMonth = new Date(selectStartDate).getMonth();
        var startDay = new Date(selectStartDate).getDate();
        var endYear = new Date(selectEndDate).getFullYear();
        var endMonth = new Date(selectEndDate).getMonth();
        var endDay = new Date(selectEndDate).getDate();
        ganntdata.useDate.push({
          startDate: new Date(startYear, startMonth, startDay, dateValue[0], 0),
          endDate: new Date(endYear, endMonth, endDay, dateValue[1], 0),
          type: value[0]
        })
      }
      this.setData({
        ganntdata,
        tempIndex: []
      })
      this.initViewDate();
    }
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: value,
      [`${key}Text`]: value.join(' '),
    });
  },
  onPickerCancel(e) {
    const {
      key
    } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log(key)
    var tempIndex = this.data.tempIndex;
    // 2/27
    if (tempIndex[0]) {
      var viewDateList = this.data.viewDateList;
      if (tempIndex.length == 2) {
        var min = tempIndex[0];
        var max = tempIndex[1];
        if (tempIndex[0] > tempIndex[1]) {
          min = tempIndex[1];
          max = tempIndex[0]
        }
        for (let i = min; i <= max; i++) {
          viewDateList[i].hour = 0;
          viewDateList[i].type = '';
        }
      } else {
        viewDateList[tempIndex[0]].hour = 0;
        viewDateList[tempIndex[0]].type = '';
      }
      this.setData({
        viewDateList,
        selectStartDate: '',
        selectEndDate: '',
        tempIndex: []
      })
    }
    console.log('picker1 cancel:');
    this.setData({
      [`${key}Visible`]: false,
    });
  },
  // 2/28
  onDateSelect(e) {
    var {
      date,
      index,
      types,
      tindex
    } = e.currentTarget.dataset;
    console.log(e)
    var type = this.data.currType;
    var year = this.data.year;
    var month = this.data.month;
    // 2/27
    var nowtime = new Date(new Date().toLocaleDateString()).getTime();
    var currtime = new Date(year, month, date).getTime();
    if (nowtime > currtime) {
      return;
    }
    if (types && types != '6') {
      var ganntdata = this.data.ganntdata;
      var tdata = ganntdata.useDate[tindex];
      var tstartDate = new Date(tdata.startDate - 0).format('yyyy-MM-dd hh:mm:ss');
      var tendDate = new Date(tdata.endDate - 0).format('yyyy-MM-dd hh:mm:ss');
      this.setData({
        detailInfoVisible: true,
        tstartDate,
        tendDate
      })
    } else {
      var viewDateList = this.data.viewDateList;
      var tempIndex = this.data.tempIndex;
      var selectStartDate = this.data.selectStartDate;
      tempIndex.push(index);
      if (tempIndex.length == 2) {
        var min = tempIndex[0];
        var max = tempIndex[1];
        if (tempIndex[0] > tempIndex[1]) {
          min = tempIndex[1];
          max = tempIndex[0]
        }
        var temp = false;
        for (let i = min; i <= max; i++) {
          if (temp) break;
          if (viewDateList[i].type != '6' && viewDateList[i].type != '') {
            temp = true;
          }
        }
        if (temp) {
          wx.showToast({
            title: '所选日期已有占用库存,请重新选择日期',
            icon: 'none'
          })
          tempIndex.pop();
          this.setData({
            tempIndex
          })
          return;
        } else {
          for (let i = min; i <= max; i++) {
            viewDateList[i].hour = MAX_WIDTH;
            viewDateList[i].type = '6';
          }
        }
      } else {
        viewDateList[index].hour = MAX_WIDTH;
        viewDateList[index].type = '6';
      }
      this.setData({
        viewDateList,
        tempIndex
      })
      // 2/28
      if (type == 'hour') {
        this.setData({
          selectStartDate: `${year}-${month - 0 + 1}-${date}`,
          selectEndDate: `${year}-${month - 0 + 1}-${date}`,
          dateVisible: true
        })
      }
      if (type == 'day') {
        if (!selectStartDate) {
          this.setData({
            selectStartDate: `${year}-${month - 0 + 1 }-${date}`,
          })
        } else {
          this.setData({
            selectEndDate: `${year}-${month - 0 + 1 }-${date}`,
            dateVisible: true
          })
        }
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})